/**
 * 
 */
package us.gaaoc.framework.util;



import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * HibernateUtil.java 
 * 
 * <p>
 * Description: Responsible for setting up the Singleton Session factory and for
 * open and closing Session(s).
 * </p>
 * 
 * 
 * @author Michael Robinson
 * @version 1.0
 */

public class HibernateUtil {

	private static final Logger LOG = Logger.getLogger(HibernateUtil.class);
	
	private static SessionFactory SESSION_FACTORY;
	public static final ThreadLocal SESSION = new ThreadLocal();
	
	// Initialize the SessionFactory
	/*
	static {
		try {
			// Create the SessionFactory
			LOG.debug("Call to HibernateUtil creating SESSION factory from static block");
			SESSION_FACTORY = new Configuration().configure().buildSessionFactory();

		} catch (Throwable ex) {
			LOG.error("Initial SessionFactory creation failed.");
			LOG.error(ex.getMessage());
			throw new ExceptionInInitializerError(ex);
		}
	}
	*/

	/**
	 * Returns a Hibernate Session instance. 
	 * 
	 * @return Session instance
	 * @throws HibernateException
	*/
	public static Session currentSession() throws HibernateException {
		Session s = (Session) SESSION.get();
/*
		// Open a new Session, if this Thread has none yet
		if (s == null || s.isOpen() == false) {
			if (SESSION_FACTORY == null) {
				// use default hibernate.cfg.xml
				try {
					LOG.debug("************Doing Hibernate Configuration b/c null SESSION_FACTORY**********");
					SESSION_FACTORY = new Configuration().configure().buildSessionFactory();
				} catch (Throwable ex) {
					LOG.error("Initial SESSION_FACTORY creation failed");
					LOG.error(ex);
					ex.printStackTrace();
					throw new ExceptionInInitializerError(ex);
				}
			}
			LOG.info("Retriving Current Session....");
			s = SESSION_FACTORY.openSession();
			SESSION.set(s);
		}
*/
		return s;
	}
 

	/**
	 * Closes the Session instance.
	 * 
	 * @throws HibernateException
	 */
	public static void closeSession() throws HibernateException {
		// get the ThreadLocal instance
		Session s = (Session) SESSION.get();
/*
		SESSION.set(null);
		if (s != null) {
			LOG.debug("Closing the SESSION");
			s.close();
		}
*/
	}

/*
	public static SessionFactory getSessionFactory() {
		return SESSION_FACTORY;
	}
*/
}
